//
//  KVNMediaCollectionViewCell.m
//  Test1
//
//  Created by KelvinYeung on 15/8/12.
//  Copyright (c) 2015年 KelvinYeung. All rights reserved.
//

#import "KVNMediaCollectionViewCell.h"

#define MAX_SCALE 5
#define MIN_SCALE 0.5;
#define SCALE_STATUS_NORMAL 0
#define SCALE_STATUS_ZOOMIN 1
#define SCALE_STATUS_ZOOMOUT 2

@interface KVNMediaCollectionViewCell()
@property UIPanGestureRecognizer *panRecognizer;
@property BOOL isReachBounds;
@property NSInteger scaleStatus;
@property (nonatomic,strong) MPMoviePlayerController *moviePlayer;//视频播放控制器
@property UIImageView * imageView;
@property UIButton *playButton;
@property NSURL *videoUrl;
@end


@implementation KVNMediaCollectionViewCell
@synthesize lastScale;
@synthesize lastTranlatePoint;
@synthesize panRecognizer;

- (instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    [self initSubviews];
    return self;
}

- (void) initSubviews{
    self.clipsToBounds = YES;
    _isReachBounds = YES;
    _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_loading"]];
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.contentView addSubview:_imageView];
    _imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    [_imageView addObserver:self forKeyPath:@"image" options:0 context:nil];
    [self reCalcImageSize];
    _orignCenter = [_imageView center];
    NSLog(@"a:%f b:%f c:%f d:%f tx:%f ty:%f",_imageView.transform.a,_imageView.transform.b,_imageView.transform.c,_imageView.transform.d, _imageView.transform.tx,_imageView.transform.ty);
    
    //放大缩小手势
    UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scaGesture:)];
    pinchRecognizer.delegate = self;
    [self addGestureRecognizer:pinchRecognizer];
    
    //慢速移动
    panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(translationImageView:)];
    panRecognizer.delegate = self;
    [self addGestureRecognizer:panRecognizer];
    
    
    //双击放大缩小手势
    UITapGestureRecognizer *doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    doubleTapGestureRecognizer.numberOfTapsRequired = 2;
    doubleTapGestureRecognizer.numberOfTouchesRequired = 1;
    [self addGestureRecognizer:doubleTapGestureRecognizer];
    
    _imageView.exclusiveTouch = YES;

    //播放按钮
    _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_playButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    [self.contentView addSubview:_playButton];
    _playButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:_playButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:_playButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
    
    UITapGestureRecognizer *playGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playVidio)];
    [_playButton addGestureRecognizer:playGestureRecognizer];
    
    
}

#pragma mark - 手势处理函数
//双击
- (void)handleDoubleTap:(UITapGestureRecognizer *) sender{

    if (_imageView.transform.a != 1.0 ) {
        [UIView animateWithDuration:0.3 animations:^{
            CGAffineTransform currentTransform = _imageView.transform;
            currentTransform.a = 1.0;
            currentTransform.d = 1.0;
            [_imageView setTransform:currentTransform];
            [_imageView setCenter:_orignCenter];
            lastScale = 1.0;
            _isReachBounds = NO;
        }];
    } else {
    
        [UIView animateWithDuration:0.3 animations:^{
            [_imageView setTransform:CGAffineTransformIdentity];
            CGAffineTransform currentTransform = _imageView.transform;
            CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, MAX_SCALE, MAX_SCALE);
            //[[(UIPinchGestureRecognizer*) sender view]setTransform:newTransform];
            [_imageView setTransform:newTransform];
            lastScale = 1.0;
            _isReachBounds = NO;
        }];
        
    
    }




}


//放大缩小
-(void)scaGesture:(id)sender {
    //[self bringSubviewToFront:[(UIPinchGestureRecognizer*)sender view]];
    //当手指离开屏幕时,将lastscale设置为1.0
    if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {

        if (_imageView.transform.a <1) {
            [UIView animateWithDuration:0.2 animations:^{
                CGAffineTransform currentTransform = _imageView.transform;
                currentTransform.a = 1.0;
                currentTransform.d = 1.0;
                [_imageView setTransform:currentTransform];
                [_imageView setCenter:_orignCenter];
                
                
            } completion:^(BOOL finished) {
                _isReachBounds = YES;
            }];
            
        }
        //左边超出边界
        else if (_imageView.center.x > _imageSize.width*_imageView.transform.a*0.5) {
            
            [UIView animateWithDuration:0.2 animations:^{
                [_imageView setCenter:
                 CGPointMake(_imageSize.width*_imageView.transform.a*0.5, _imageView.center.y)];
            }];
        }else if ( _imageSize.width *_imageView.transform.a*0.5 + _imageView.center.x < self.frame.size.width){
            //右边超出边界
            [UIView animateWithDuration:0.2 animations:^{
                [_imageView setCenter:
                 CGPointMake(self.frame.size.width - _imageSize.width*_imageView.transform.a*0.5, _imageView.center.y)];
            } completion:^(BOOL finished) {
                _scaleStatus = SCALE_STATUS_NORMAL;
            }];
        
        }
        
        //如果图片高度小于图片imageView高度，则弹加中心
        if (_imageSize.height*_imageView.transform.a <self.frame.size.height) {
            [UIView animateWithDuration:0.5 animations:^{
                [_imageView setCenter:_orignCenter];
            }];
        }
        //如果图片高度大于图片，且图片的顶部小于image顶图，则将图片顶部弹回丐imge顶部对齐，底部亦然；
        else if (_imageView.center.y > _imageSize.height*_imageView.transform.d*0.5) {
            //顶部
            [UIView animateWithDuration:0.5 animations:^{
                [_imageView setCenter:CGPointMake(_imageView.center.x, _imageSize.height*_imageView.transform.d*0.5)];
                
            }];
        }
        else if (_imageSize.height *_imageView.transform.d*0.5 + _imageView.center.y < self.frame.size.height){
            //底部
            [UIView animateWithDuration:0.5 animations:^{
                [_imageView setCenter:CGPointMake(_imageView.center.x,self.frame.size.height - _imageSize.height *_imageView.transform.d*0.5)];
            }];
            
        }
        
        
       //如果超出最大放大倍数，则缩回到最大放大倍数；
        if (_imageView.transform.a > MAX_SCALE) {
            [UIView animateWithDuration:0.2 animations:^{
                CGAffineTransform currentTransform = _imageView.transform;
                currentTransform.a = MAX_SCALE;
                currentTransform.d = MAX_SCALE;
                [_imageView setTransform:currentTransform];
            }];
        }
        
        
        lastScale = 1.0;
        return;
    }
    

    CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);
    //CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
    CGAffineTransform currentTransform = _imageView.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
    //[[(UIPinchGestureRecognizer*) sender view]setTransform:newTransform];
    [_imageView setTransform:newTransform];
    lastScale = [(UIPinchGestureRecognizer*)sender scale];
    
    

}


//移动
-(void)translationImageView:(UIPanGestureRecognizer *)sender {
    //视频暂停
    [_moviePlayer pause];
    
    CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self];
    //当手指按下时，touch开始
    if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
        lastTranlatePoint = [_imageView center];
        
    }
    
   
    if ((lastTranlatePoint.x+translatedPoint.x) > _imageSize.width*_imageView.transform.a*0.5
        || _imageSize.width *_imageView.transform.a*0.5 + (lastTranlatePoint.x+translatedPoint.x) < self.frame.size.width) {
        
       //只能上下移动
        //如果图片高度小于图片imageView高度，只能左右移动
        if (_imageSize.height*_imageView.transform.a <self.frame.size.height) {
            translatedPoint = CGPointMake(lastTranlatePoint.x, lastTranlatePoint.y);
        }else{
             translatedPoint = CGPointMake(lastTranlatePoint.x, lastTranlatePoint.y+translatedPoint.y);
        }
       
        _isReachBounds = YES;
        
    }else{
        //如果图片高度小于图片imageView高度，只能左右移动
        if (_imageSize.height*_imageView.transform.a <self.frame.size.height) {
             translatedPoint = CGPointMake(lastTranlatePoint.x+translatedPoint.x, lastTranlatePoint.y);
        }else{
            translatedPoint = CGPointMake(lastTranlatePoint.x+translatedPoint.x, lastTranlatePoint.y+translatedPoint.y);
        }

        
        
        _isReachBounds = NO;
    }

    [_imageView setCenter:translatedPoint];
    //[self showOverlayWithFrame:_imageView.frame];

    
    
    //当手指抬起时，touch结束
    if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) {
        //如果图片高度小于图片imageView高度，则弹加中心
        if (_imageSize.height*_imageView.transform.a <self.frame.size.height) {
            [UIView animateWithDuration:0.5 animations:^{
                [_imageView setCenter:_orignCenter];
            }];
        }
        //如果图片高度大于图片，且图片的顶部小于image顶图，则将图片顶部弹回丐imge顶部对齐，底部亦然；
        else if (_imageView.center.y > _imageSize.height*_imageView.transform.d*0.5) {
            //顶部
            [UIView animateWithDuration:0.5 animations:^{
                [_imageView setCenter:CGPointMake(_imageView.center.x, _imageSize.height*_imageView.transform.d*0.5)];
                
            }];
        }
        else if (_imageSize.height *_imageView.transform.d*0.5 + _imageView.center.y < self.frame.size.height){
            //底部
            [UIView animateWithDuration:0.5 animations:^{
                [_imageView setCenter:CGPointMake(_imageView.center.x,self.frame.size.height - _imageSize.height *_imageView.transform.d*0.5)];
            }];
        
        }
        
    }
}




//UIViewContentModeScaleAspectFit后图片大小
- (void) reCalcImageSize{
    CGFloat scale = 1.0;
    if (_imageView.image.size.width/_imageView.image.size.height>self.frame.size.width/self.frame.size.height){
    
        scale = _imageView.image.size.width/self.frame.size.width;
    }else {
        scale = _imageView.image.size.height /self.frame.size.height;
    }
    _imageSize= CGSizeMake(_imageView.image.size.width/scale , _imageView.image.size.height/scale);
    
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([keyPath isEqualToString:@"image"]){
        [self reCalcImageSize];
        [_imageView setCenter:_orignCenter];
    }
}








- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //[self.nextResponder touchesEnded:touches withEvent:event];
}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
   /*
    if (_isReachBounds){
        [self.nextResponder touchesBegan:touches withEvent:event];
    }
*/
}


#pragma mark - UIGestureRecognizer代理方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return _isReachBounds;
}

/*
-(void)resetImageView{
    [_imageView setHidden:YES];
    [_imageView setTransform:CGAffineTransformIdentity];
    [UIView animateWithDuration:1 animations:^{
         [_imageView setHidden:NO];

    }completion:^(BOOL finished) {
       
    }];
    
    
}
 */

#pragma mark - 视频播放
- (void)playVidio{
    
    //初始化播放器
    if (!_moviePlayer) {
        _moviePlayer=[[MPMoviePlayerController alloc]init];
        _moviePlayer.view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self addSubview:_moviePlayer.view];

        
    }
    [_imageView setHidden:YES];
    [_playButton setHidden:YES];
    _moviePlayer.view.frame=CGRectMake(0, 0, _imageSize.width, _imageSize.height);
    [_moviePlayer.view setCenter:_orignCenter];
    [_moviePlayer.view setHidden:NO];
    [_moviePlayer setContentURL:_videoUrl];
    [_moviePlayer play];

}

/**
 *  添加通知监控媒体播放控制器状态
 */
-(void)addNotification{
    
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
    
}


/**
 *  播放状态改变，注意播放完成时的状态是暂停
 *
 *  @param notification 通知对象
 */
-(void)mediaPlayerPlaybackStateChange:(NSNotification *)notification{
    switch (self.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放...");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放.");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放.");
            break;
        default:
            NSLog(@"播放状态:%li",(long)self.moviePlayer.playbackState);
            break;
    }
}

/**
 *  播放完成
 *
 *  @param notification 通知对象
 */
-(void)mediaPlayerPlaybackFinished:(NSNotification *)notification{
    NSLog(@"播放完成.%li",(long)self.moviePlayer.playbackState);
    [_imageView setHidden:NO];
    [_playButton setHidden:NO];
    [_moviePlayer.view setHidden:YES];
    
}


-(void)setImageFromURL:(NSURL *)url{
    [_imageView setImageFromURL:url];
    [_playButton setHidden:YES];
    
    if (_moviePlayer) {
        [_playButton setHidden:YES];
        [_moviePlayer setContentURL:nil];
        [_moviePlayer.view setHidden:YES];
    }
    
    
    //以下考虑到cell重用，重设_imageView的transform
    [_imageView setHidden:YES];
    [_imageView setTransform:CGAffineTransformIdentity];
    [UIView animateWithDuration:1 animations:^{
        [_imageView setHidden:NO];
        
    }completion:^(BOOL finished) {
        
    }];
    
}

-(void)setVideoFromURL:(NSURL *)videoUrl withDefaultImageFromURL:(NSURL *)imageUrl{
    if (_moviePlayer) {
        [_moviePlayer.view setHidden:YES];
    }
    _videoUrl = videoUrl;
    [_imageView setImageFromURL:imageUrl];
    [_imageView setHidden:NO];
    [_playButton setHidden:NO];
    
}

@end
